package me.yxy.mobanddd.domain.eventhandler;

import me.yxy.mobanddd.domain.events.ShipmentOrdersChangedEvent;
import me.yxy.mobanddd.domain.shipment.Shipment;
import me.yxy.mobanddd.domain.shipment.ShipmentRepository;
import me.yxy.mobanddd.domain.shipment.ShipmentStatus;
import me.yxy.mobanddd.domain.transportorder.TransportOrderRepository;
import me.yxy.mobanddd.domain.transportorder.TransportOrderStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * 运单修改事件处理类
 */
@Component
public class ShipmentOrderChangedEventHandler implements ApplicationListener<ShipmentOrdersChangedEvent> {

    static final Logger logger = LoggerFactory.getLogger(ShipmentOrderChangedEventHandler.class);

    @Autowired
    TransportOrderRepository transportOrderRepository;

    @Autowired
    ShipmentRepository shipmentRepository;

    @Override
    public void onApplicationEvent(ShipmentOrdersChangedEvent event) {

        System.out.println(Thread.currentThread());
        logger.info("收到消息:{}",event);

        //如果发生在调度单的INIT阶段，则无所谓 END
        Optional<Shipment> shipmentOp = shipmentRepository.findById(event.getShipmentId());
        Shipment shipment = shipmentOp.get();
        if(shipment==null) return;


        //根据调度单的当前状态，进行不同的重算处理
        switch (shipment.getStatus()){

            //如果在COMMFIRM，则要重新触发确认操作
            case COMFIRMED:
                shipment.comfirm();
                break;

            //如果在ONWAY，则要只要重新计算总里程
            case ONWAY:
                handlerOnway(shipment);
                break;
            default:break;
        }

    }

    private void handlerOnway(Shipment shipment) {

        //重新计算里程
        shipment.recalculateMileage();

        //如果当前所有运单都已经运抵了，那么直接修改当前调度单为已运抵
        Integer count = transportOrderRepository.countByStatusAndShipment(TransportOrderStatus.FINISHED,shipment);
        if(shipment.getTransportOrders().size() == count){
            shipment.setStatus(ShipmentStatus.FINISHED);
        }
    }
}
